
Page({

  /**
   * 页面的初始数据
   */
  data: {
    canvasWidth: 600,
    canvasHeight: 600,
    imgpath: '',
    items: ['煲仔饭', '兰州拉面', '肯德基'],
    duration: '2s',
    positions: [],  //文字旋转角度
    currentItem: 0, //当前选项
    picRevolve: 0,  //图片旋转角度
    baseResolve: 0, //转盘旋转角度
    addValue:"",
    focus:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getItems()
  },

  /**
  * 生命周期函数--监听页面显示
  */
  onShow: function () {
    this.getItems()
  },

  //从本地缓存中读取数据，初始化items
  getItems:function(){
    let that = this
    try{
      var value = wx.getStorageSync("itemArray")
      //缓存中有itemArray选项
      if(value){
        // 数组不为空时给items赋值
        if(value.length != 0){
          that.setData({
            items: value
          })
        }else{
          //数组为空时什么也不做，就用默认的值就行了
        }
        // console.log(value)
        that.createCanvas()
        that.parsePosition()
      }else{
        // 缓存中没有itemArray,就用默认的值
        console.log('获取失败')
        that.createCanvas()
        that.parsePosition()
      }
    }catch(e){
      // 调用getStorageSync失败
      that.createCanvas()
      that.parsePosition()
    }
  },


  //随机颜色
  getRandomColor: function() {
    var r = parseInt(Math.random() * 256);
    var g = parseInt(Math.random() * 256);
    var b = parseInt(Math.random() * 256);
    return 'rgb(' + r + ',' + g + ',' + b + ')';
  },
  // 生成一张图片，更新imgPath
  createCanvas: function() {
    var number = this.data.items.length
    var ctx = wx.createCanvasContext('mycanvas')
    var angle = Math.PI * 2 / number
    var start = 0;
    var end = angle;
    for (var i = 0; i < number; i++) {
      ctx.beginPath()
      ctx.moveTo(300, 300);
      ctx.arc(300, 300, 300, start, end);
      ctx.closePath()
      ctx.fillStyle = this.getRandomColor();
      ctx.fill()
      start = end;
      end += angle
    }
    ctx.draw(false, () => {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        destHeight: 600,
        destWidth: 600,
        quality:1,
        success: res => {
          this.setData({
            imgpath: res.tempFilePath,
            picRevolve: -90 - 360 / number / 2
          })
        }
      })
    });
  },
  //文字旋转角度,更新positions、picRevolve
  parsePosition: function() {
    var number = this.data.items.length;
    var deg = 360 / number;
    var arr = []
    for (var i = 0; i < number; i++) {
      arr.push(deg*i)
    }
    this.setData({
      positions: arr,
      picRevolve: -90 - deg / 2
    })
  },

  // 抽奖,更新baseRevolve
  choujiang: function() {
    var number = this.data.items.length;
    var deg = 360 / number;
    // 获取1到number之间的随机数
    var random = Math.ceil(Math.random() * number);
    //让base复位
    this.setData({
      baseRevolve: 0,
      duration: '0s'
    }, function() {
      //让base旋转
      var newCurrentItem = number - random
      console.log('结果是'+newCurrentItem)
      var newBaseRevolve = deg * random + 720
      this.setData({
        baseRevolve: newBaseRevolve,
        currentItem: newCurrentItem,
        duration: '3s'
      })
    })
  },

  // 删除选项
  deleRestaurant: function(event) {
    var r = event.target.dataset.item
    var newArr = []
    for (let i of this.data.items) {
      // console.log(i)
      if (i != r) {
        newArr.push(i)
      }
    }
    if(newArr.length==0){
      wx.showToast({
        title: '就剩一个了，别删啦',
        icon: 'none',
      })
      return
    }
    wx.setStorage({
      key: 'itemArray',
      data: newArr,
    })
    this.setData({
      items: newArr,
      baseResolve: 0
    }, () => {
      this.createCanvas()
      this.parsePosition()
    })
  },

  // 添加选项
  addRestaurant:function(e){
    var val = e.detail.value.restaurantName
    wx.cloud.init()
    wx.cloud.callFunction({
      name:'msgCheck',
      data:{
        msg:val
      }
    }).then(res=>{
      if(res.result){
        var newArr = []
        var isRepeat = false
        var items = this.data.items
        for (var i in items) {
          newArr.push(items[i])
          if (items[i] === val) {
            isRepeat = true
          }
        }
        // 选项不能为空，不能重复
        if (val.length === 0) {
          wx.showToast({
            title: '这是个空选项',
            icon: 'none',
          })
          return
        } else if (isRepeat) {
          wx.showToast({
            title: '不能重复添加',
            icon: 'none',
          })
          return
        } else {
          newArr.push(val)
          // 保存到本地
          wx.setStorage({
            key: 'itemArray',
            data: newArr,
          })
          // 更新数据
          this.setData({
            items: newArr,
            baseResolve: 0,
            addValue: ""
          }, () => {
            // 重新画图和定位
            this.createCanvas()
            this.parsePosition()
          })
        }
      }else{
        wx.showToast({
          title: '包含不合法内容',
          icon: 'none',
        })
        return
      }
    })
  }
})